package com.tea.dao;

import com.tea.entity.Review;
import com.tea.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class ReviewDao {
    // 添加评论
    public int addReview(Review review) throws Exception {
        String sql = "INSERT INTO review (product_id, user_id, content, rating, order_id, create_time) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, review.getProductId());
            pstmt.setLong(2, review.getUserId());
            pstmt.setString(3, review.getContent());
            pstmt.setInt(4, review.getRating());

            // Handle order_id - set to NULL if 0 or negative (for general product reviews)
            if (review.getOrderId() <= 0) {
                pstmt.setNull(5, java.sql.Types.BIGINT);
            } else {
                pstmt.setLong(5, review.getOrderId());
            }

            pstmt.setTimestamp(6, new Timestamp(review.getCreateTime().getTime()));
            return pstmt.executeUpdate();
        }
    }

    // 根据商品ID查询评论
    public List<Review> getReviewsByProductId(Long productId) throws Exception {
        List<Review> reviews = new ArrayList<>();
        String sql = "SELECT r.review_id, r.product_id, r.user_id, r.content, r.rating, r.order_id, r.create_time, u.username " +
                     "FROM review r JOIN user u ON r.user_id = u.user_id " +
                     "WHERE r.product_id = ? ORDER BY r.create_time DESC";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, productId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Review review = new Review();
                    review.setReviewId(rs.getLong("review_id"));
                    review.setProductId(rs.getLong("product_id"));
                    review.setUserId(rs.getLong("user_id"));
                    review.setContent(rs.getString("content"));
                    review.setRating(rs.getInt("rating"));

                    // Handle nullable order_id
                    Long orderId = rs.getObject("order_id", Long.class);
                    review.setOrderId(orderId != null ? orderId : 0);

                    review.setUsername(rs.getString("username"));
                    Timestamp createTime = rs.getTimestamp("create_time");
                    if (createTime != null) {
                        review.setCreateTime(new java.util.Date(createTime.getTime()));
                    }
                    reviews.add(review);
                }
            }
        }
        return reviews;
    }

    // 检查用户是否已经对该商品发表过评论（非订单评论）
    public boolean hasUserReviewedProduct(Long userId, Long productId) throws Exception {
        String sql = "SELECT COUNT(*) FROM review WHERE user_id = ? AND product_id = ? AND order_id IS NULL";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, userId);
            pstmt.setLong(2, productId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1) > 0;
                }
            }
        }
        return false;
    }
}